#include <vector>
#include <map>
#include <queue>

using namespace std;

class Solution
{
    typedef pair<int, int> PII;
    struct com
    {
        bool operator()(PII &A, PII &B)
        {
            return A.second < B.second;
        }
    };

public:
    vector<int> topKFrequent(vector<int> &nums, int k)
    {
        vector<int> ret;
        map<int, int> m;
        priority_queue<PII, vector<PII>, com> p;
        for (auto &x : nums)
        {
            ++m[x];
        }

        for (auto &x : m)
        {
            p.push({x.first, x.second});
        }

        while (k--)
        {
            auto tmp = p.top();
            p.pop();
            ret.push_back(tmp.first);
        }

        return ret;
    }
};